package com.rc.evcharger.utils;

import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.dto.msg.TerminalMessage;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class DataDealExp {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public final String START_SIGN = "68";// 帧起始符
    public final String END_SIGN = "16";// 帧结束符
    public final String START = "68";
    public final String END = "16";

    @Autowired
    private RedisService redisService;

    public String dealMsg01(String body) {
        System.out.println(body);
        return body;
    }

    /**
     * 处理数据分包，断针的问题.
     *
     * @param ctx
     * @param body
     * @return
     */
    public String dealMsg(ChannelHandlerContext ctx, String body) {
        String key = DataUtil.getChannelIdKey(ctx.channel().id().asLongText());
        TerminalMessage szTerminalMessage = null;
        String[] bcdCodes = body.split(DataUtil.SPLIT);
        List<Integer> starts = new ArrayList<>();
        List<Integer> ends = new ArrayList<>();
        List<TerminalMessage> result = new ArrayList<>();
        for (int i = 0; i < bcdCodes.length; i++) {
            if (bcdCodes[i].equals(START)) {
                starts.add(i);
                continue;
            }
            if (bcdCodes[i].equals(END)) {
                ends.add(i);
                continue;
            }
        }
        if (starts.size() < 1 || ends.size() < 1) {
            logger.warn("异常数据3：" + body);
            return dealBody(ctx, body);
        }
        for (Integer start : starts) {
            for (Integer end : ends) {
                try {
                    szTerminalMessage = new TerminalMessage(start, end, bcdCodes);
                    // System.out.println(szTerminalMessage.toString());
                    if (!isExist(result, szTerminalMessage)) {
                        result.add(szTerminalMessage);
                    }
                } catch (Exception e) {
                    // e.printStackTrace();
                }
            }
        }
        if (result.size() < 1) {
            logger.warn("异常数据5：" + body);
            return dealBody(ctx, body);
        }
        if (redisService.getRedis(key) != null) {
            redisService.remove(key);
        }
        return body;
    }

    private static boolean isExist(List<TerminalMessage> result, TerminalMessage stm) {
        for (TerminalMessage stm0 : result) {
            // if(stm0.getContral().equals(stm.getContral()) &&
            // stm0.getLength().equals(stm.getLength())){
            if (stm0.toString().equals(stm.toString())) {
                return true;
            }
        }

        return false;
    }

    private String dealBody(ChannelHandlerContext ctx, String body) {
        String key = DataUtil.getChannelIdKey(ctx.channel().id().asLongText());
        if (redisService.getRedis(key) == null) {
            if (body.indexOf(END) == -1) {
                redisService.putRedis(key, body.trim());
            } else {
                body = body.substring(body.indexOf(END) + 2);
                if (body != null && body.length() > 1) {
                    redisService.putRedis(key, body);
                }
            }
            return body;
        } else {
            // 异常数据redis中进行拼接，然后在判断数据;
            redisService.putRedis(key, redisService.getRedis(key) + DataUtil.SPLIT + body);
            body = redisService.getRedis(key);
            String subData = null;
            if (body.indexOf(END) != -1) {
                String body0 = body.substring(0, body.indexOf(END) + 2).trim();
                subData = body.substring(body0.length()).trim();
                body = body0;
                if (subData != null && subData.length() > 1) {
                    redisService.putRedis(key, subData);
                } else {
                    redisService.remove(key);
                }
            } else {
                logger.warn("异常数据3：" + body);
                return body;
            }
            return body;
        }

    }

    public static void main(String[] args) {
        System.out.println("0123456".indexOf("12"));
        System.out.println("0123456".substring(0, 1 + 2));
    }
}
